package com.bilibili.servlet;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bilibili.entity.Comment;
import com.bilibili.service.CommentService;
import com.bilibili.service.impl.CommentServiceImpl;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/commentToo.do")
public class CommentTooServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private CommentService commentService = new CommentServiceImpl();
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置响应头
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        Map<String, Object> result = new HashMap<>();
        
        try {
            // 读取请求体
            BufferedReader reader = request.getReader();
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
            
            String requestBody = sb.toString();
            if (requestBody == null || requestBody.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "请求体不能为空");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                objectMapper.writeValue(response.getWriter(), result);
                return;
            }
            
            // 解析评论对象
            Comment comment = objectMapper.readValue(requestBody, Comment.class);
            
            // 增强参数验证
            if (comment.getUserId() <= 0) {
                result.put("success", false);
                result.put("message", "用户ID必须为正整数");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                objectMapper.writeValue(response.getWriter(), result);
                return;
            }
            
            if (comment.getContent() == null || comment.getContent().trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "评论内容不能为空");
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                objectMapper.writeValue(response.getWriter(), result);
                return;
            }
            
            // 调用服务层添加评论
            int commentId = commentService.addComment(comment);
            
            if (commentId > 0) {
                // 设置评论ID并返回
                comment.setCommentId(commentId);
                result.put("success", true);
                result.put("message", "评论添加成功");
                result.put("data", comment);
                response.setStatus(HttpServletResponse.SC_CREATED);
            } else {
                result.put("success", false);
                result.put("message", "评论添加失败，请重试");
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            }
        } catch (JsonMappingException e) {
            String fieldName = e.getPath() != null && !e.getPath().isEmpty() 
                ? e.getPath().get(0).getFieldName() 
                : "未知字段";
            
            result.put("success", false);
            result.put("message", "字段格式错误: " + fieldName + " - " + e.getOriginalMessage());
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            e.printStackTrace();
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "评论添加异常: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            objectMapper.writeValue(response.getWriter(), result);
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 设置响应头
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        
        Map<String, Object> result = new HashMap<>();
        try {
            String action = request.getParameter("action");
            
            if ("list".equals(action)) {
                // 获取视频评论列表
                getCommentsByVideoId(request, response, result);
            } else if ("replies".equals(action)) {
                // 获取回复列表
                getRepliesByParentId(request, response, result);
            } else if ("like".equals(action)) {
                // 点赞评论
                likeComment(request, response, result);
            } else {
                // 默认获取视频评论列表
                getCommentsByVideoId(request, response, result);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "获取评论异常: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            e.printStackTrace();
        } finally {
            objectMapper.writeValue(response.getWriter(), result);
        }
    }
    
    // 获取视频评论列表
    private void getCommentsByVideoId(HttpServletRequest request, HttpServletResponse response, Map<String, Object> result) 
            throws Exception {
        String videoIdParam = request.getParameter("videoId");
        if (videoIdParam == null || videoIdParam.isEmpty()) {
            result.put("success", false);
            result.put("message", "缺少视频ID参数");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        
        int videoId = Integer.parseInt(videoIdParam);
        List<Comment> comments = commentService.getCommentsByVideoId(videoId, 0, 0);
        
        if (comments != null) {
            result.put("success", true);
            result.put("message", "获取评论成功");
            result.put("data", comments);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            result.put("success", false);
            result.put("message", "获取评论失败");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    // 获取回复列表
    private void getRepliesByParentId(HttpServletRequest request, HttpServletResponse response, Map<String, Object> result) 
            throws Exception {
        String parentIdParam = request.getParameter("parentId");
        if (parentIdParam == null || parentIdParam.isEmpty()) {
            result.put("success", false);
            result.put("message", "缺少父评论ID参数");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        
        int parentId = Integer.parseInt(parentIdParam);
        List<Comment> replies = commentService.getRepliesByParentId(parentId);
        
        if (replies != null) {
            result.put("success", true);
            result.put("message", "获取回复成功");
            result.put("data", replies);
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            result.put("success", false);
            result.put("message", "获取回复失败");
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
    
    // 点赞评论
    private void likeComment(HttpServletRequest request, HttpServletResponse response, Map<String, Object> result) 
            throws Exception {
        String commentIdParam = request.getParameter("commentId");
        if (commentIdParam == null || commentIdParam.isEmpty()) {
            result.put("success", false);
            result.put("message", "缺少评论ID参数");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        
        int commentId = Integer.parseInt(commentIdParam);
        boolean success = commentService.likeComment(commentId);
        
        result.put("success", success);
        result.put("message", success ? "点赞成功" : "点赞失败");
        response.setStatus(success ? HttpServletResponse.SC_OK : HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
}